package com.mvc.utils;

import java.security.Key;  
import java.security.NoSuchAlgorithmException;  
import java.security.SecureRandom;  
import javax.crypto.Cipher;  
import javax.crypto.KeyGenerator;  
import javax.crypto.SecretKey;  
import javax.crypto.spec.SecretKeySpec;  

  
/**
 * AES非对称加密
 * 非对称加密
 * 公钥加密
 * 私钥解密
 * 编码方式为utf-8
 * @author qingjie 2015-09-08
 *
 */
public class PublicSecret {  
      
    private static final PublicSecret instance = new PublicSecret();  
  
    /**
     * 构造方法
     */
    private PublicSecret() {  
  
    }  
  
    
    public static PublicSecret getInstance() {  
        return instance;  
    }  
  
    /**
     * 生成key
     * @param key
     * @return
     * @throws NoSuchAlgorithmException
     */
    private Key initKeyForAES(String key) throws NoSuchAlgorithmException {  
        if (null == key || key.length() == 0) {  
            throw new NullPointerException("˽Կ����Ϊ��");  
        }  
        SecretKeySpec key2 = null;  
        try {  
            KeyGenerator kgen = KeyGenerator.getInstance("AES");  
            kgen.init(128, new SecureRandom(key.getBytes()));  
            SecretKey secretKey = kgen.generateKey();  
            byte[] enCodeFormat = secretKey.getEncoded();  
            key2 = new SecretKeySpec(enCodeFormat, "AES");  
        } catch (NoSuchAlgorithmException ex) {  
            throw new NoSuchAlgorithmException();  
        }  
        return key2;  
  
    }  
  
    /** 
     * 公钥
     * AES加密算法，不受密钥长度限制 
     * @param content 
     * @param key 
     * @return 
     */  
    public String encryptAES(String content, String key){  
        try{  
            SecretKeySpec secretKey = (SecretKeySpec) initKeyForAES(key);  
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器  
            byte[] byteContent = content.getBytes("gbk"); //设置字符类型
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);// 初始化  
            byte[] result = cipher.doFinal(byteContent);  
            return asHex(result); // 加密  
        }  
        catch (Exception e){  
            e.printStackTrace();  
        }  
        return null;  
    }  
  
    /** 
     * 私钥解密
     * aes解密算法，不受密钥长度限制 
     * @param content 
     * @param key 
     * @return 
     */  
    public String decryptAES(String content, String key){  
        try{  
            SecretKeySpec secretKey = (SecretKeySpec) initKeyForAES(key);  
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器  
            cipher.init(Cipher.DECRYPT_MODE, secretKey);// 初始化  
            byte[] result = cipher.doFinal(asBytes(content));  //解密
            return new String(result,"UTF-8"); // 加上编码方式，要不中文会乱码
        }  
        catch (Exception e){  
            e.printStackTrace();  
        }  
        return null;  
    }  
  
    /** 
     * 将2进制数值转换为16进制字符串 
     * @param buf 
     * @return 
     */  
    public String asHex(byte buf[]){  
        StringBuffer strbuf = new StringBuffer(buf.length * 2);  
        int i;  
        for (i = 0; i < buf.length; i++){  
            if (((int) buf[i] & 0xff) < 0x10)  
                strbuf.append("0");  
            strbuf.append(Long.toString((int) buf[i] & 0xff, 16));  
        }  
        return strbuf.toString();  
    }  
      
      
    /** 
     * 将16进制转换2进制
     * @param hexStr 
     * @return 
     */ 
    public byte[] asBytes(String hexStr) {  
        if (hexStr.length() < 1)  
            return null;  
        byte[] result = new byte[hexStr.length() / 2];  
        /**
         * 循环进行转换
         */
        for (int i = 0; i < hexStr.length() / 2; i++){  
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);  
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),16);  
            result[i] = (byte) (high * 16 + low);  
        }  
        return result;  
    }  
  
    /**
     * 测试main
     * @param args
     */
    public static void main(String[] args)  {  
    	PublicSecret crypt = PublicSecret.getInstance();        
        String content = "[{\"patient\":\"李某\",\"sex\":0,\"age\":60,\"address\":\"南宁市青秀区某小区\",\"tellNum\":\"07710000000\",\"phoneNum\":\"18989898989\",\"weixin\":\"laolitou60\",\"email\":\"3939@qq.com\",\"firstImpression\":\"良好\",\"medicalNow\":\"不清楚\",\"medicalHis\":\"主要现病史\",\"treatment\":\"主要既往史\",\"diagnosis\":\"诊断结果\",\"check\":\"检查结果\",\"recoveryAdv\":\"治疗建议\"}]";  
        System.out.println(crypt.encryptAES(content, "20150906"));  
        String dcontent = "2e383a7862635587b122e03dc0fd3a27a8ff964d67c187d56d2252b76b1af08a5ae96632c653aa92acd06f794071af9ed3146dd5462f1399b109466e89afb7c8394338d6b9d750a8fa5321d0cf6c3955ec69c9ee667d9bcddd1cad5e681ac3f2a9a627d3f09c63db942246514ee7169b9b64a04f3076e99dc5e258169af6ff0e4df79ae445e8775e1a688ee9b1534f4751d399ac5d6c8e929e737c5e887d7895e3c84d0c54844be56836e27494a2bbac574bf400fa9f040fe2733fea1d886799ae6fa81ac4add2f167fc921114035e769ca12431448a6586824d90338973ba5b695c0e89d14d2a1bd2306276666c9ba295d168114ccafa86b42c692b691bfcd2f975266c7e4741b997b6ff0a3cc1b312db2463427cfd53422014aad43df6416c53d64da3f46b53d934bd56ce728292e69d74282ccfa74de8394fafaef732b3261c84ae61691b02937200b9ba87f5abf0072bc42286620fd910e3593e6794918bff3a55364cb6e9006805c0f3bdff0be36c7c6e67cfe0ec68055256e5c4cf41f44ca65af3f1fe2e21e19ffaf2397afb09067747f2fcc09caf7823346808bee8838d426a90fef826c164dcd6876f5cfd4a0227c720988a466e4c515494affacddb32da5885bda54a80348b22acad6319f2bee37d7e96f346910547fd3bd0233958346b651093c7a7a31441b4a6f0192611df8587afc6f6a3059a8e8f71c59ab5f2489e4467b6ecdd197a7ee0e2d3c9944495004520a9d486a366940911059330cb";  
        System.out.println(crypt.decryptAES(dcontent, "20150906"));    
    }  
} 
